package com.haozi.ehub.core.handler;

import java.time.LocalDateTime;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;


/**
 * 自动填充
 * @author terry
 * @date Created in 2020/9/10 17:23
 * @version 1.0
 */
@Slf4j
@Component
public class MybatisMetaObjectHandler implements MetaObjectHandler {
	private static final Logger logger = 
			LoggerFactory.getLogger(MybatisMetaObjectHandler.class);
	@Override
	public void insertFill(MetaObject metaObject) {
		logger.info("Enter auto fill method when insert");
		//是否存在sex字段
		boolean hasSex = metaObject.hasSetter("sex");
		if(hasSex){
			//默认自动填充性别为未设置
			//原來的寫法，但是官方說有BUG推薦下面的寫法
			//fillStrategy(metaObject,"sex", -1);
			strictInsertFill(metaObject,"sex",Integer.class, -1);
		}
		//是否存在createTime字段
		boolean hasCreateTime = metaObject.hasSetter("createTime");
		if(hasCreateTime){
			//默认自动填充时间为当前时间
			//原來的寫法，但是官方說有BUG推薦下面的寫法
			/*fillStrategy(metaObject,"createTime", LocalDateTime.now());*/
			strictInsertFill(metaObject,"createTime",LocalDateTime.class, LocalDateTime.now());
		}

		//是否存在modifyTime字段
		boolean hasModifyTime = metaObject.hasSetter("modifyTime");
		if(hasModifyTime){
			//默认自动填充时间为当前时间
			//原來的寫法，但是官方說有BUG推薦下面的寫法
			/*fillStrategy(metaObject,"modifyTime", LocalDateTime.now());*/
			strictInsertFill(metaObject,"modifyTime",LocalDateTime.class,LocalDateTime.now());
		}

		//是否存在logicDelete字段
		boolean hasLogicDelete = metaObject.hasSetter("logicDelete");
		if(hasLogicDelete){
			//默认自动填充逻辑删除为未删除
			//fillStrategy(metaObject,"logicDelete",0);
			strictInsertFill(metaObject,"logicDelete",Integer.class, 0);
		}


	}

	@Override
	public void updateFill(MetaObject metaObject) {
		logger.info("Enter auto fill method when update");
		boolean hasLogicDelete = metaObject.hasSetter("logicDelete");
		if(hasLogicDelete){
			//默认自动填充逻辑删除为未删除
			//fillStrategy(metaObject,"logicDelete",0);
			strictUpdateFill(metaObject,"logicDelete",Integer.class, 0);
		}
	}

}
